package cn.yuli.redis.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.yuli.redis.mapper.UserMapper;
import cn.yuli.redis.model.User;
import cn.yuli.redis.service.CacheService;
import cn.yuli.redis.service.UserService;
//@Service
public class UserServiceImpl implements UserService {
	public static Logger logger = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	private UserMapper userMpper;//usermapper接口
	@Autowired
	private CacheService cs;//缓存实现
	@Transactional
	public User addUser(User user) {
		userMpper.insert(user);
		logger.info("向数据库添加用户");
		//添加缓存
		cs.cachePut(user.getId(), user);
		return user;
	}
	@Transactional
	public void deleteUser(String userId) {
		userMpper.deleteByPrimaryKey(userId);
		//移除缓存
		cs.cacheRemove(userId);
		
	}
	@Transactional
	public User updateUser(User user) {
		userMpper.updateByPrimaryKeySelective(user);
		//覆盖缓存
		cs.cachePut(user.getId(), user);
		return user;
	}
	@Transactional(readOnly=true)
	public User queryUser(String userId) {
		User rUser = cs.cacheResult(userId);
		//判断缓存是否存在，存在就返回redis里的user
		if(rUser != null){
			logger.info("从缓存里取得数据");
			return rUser;
		}
		//不存在就查询数据库并将user放进缓存里
		logger.info("从数据库里取得用户");
		User user = userMpper.selectByPrimaryKey(userId);
		cs.cachePut(userId, user);
		return user;
	}

}
